package com.kky.pp

import android.app.ActivityManager
import android.app.Application
import android.os.Process
import android.util.Log
import com.appsflyer.AppsFlyerConversionListener
import com.appsflyer.AppsFlyerLib
import com.custom.base.config.BaseConfig
import com.kky.pp.dot.DotLogUtil
import com.kky.pp.http.CommonHttpResutHead
import com.kky.pp.http.CommonRequest
import com.kky.pp.common.OpenUpBuyMember
import com.zhy.autolayout.config.AutoLayoutConifg
import io.rong.dot.DotInit
import io.rong.dot.listener.ImDotExecuteListener
import io.rong.imkit.IMCenter
import io.rong.imkit.SpName
import io.rong.imkit.pay.IMRegidterPayListener
import io.rong.imlib.RongCoreClient
import io.rong.imlib.model.InitOption
import io.rong.imlib.model.InitOption.AreaCode
import io.rong.push.RongPushClient
import io.rong.push.pushconfig.PushConfig
import org.json.JSONObject


/**
 * 作者：
 * 日期：2022/3/1
 * 说明：
 */
class App : Application() {
    private var isDebug = false
    private var source = ""

    companion object {
        var app: App? = null
        var openUpBuyMember: OpenUpBuyMember? = null
    }

    override fun onCreate() {
        super.onCreate()
        app = this
        AutoLayoutConifg.getInstance().useDeviceSize()
        initTextAndFormal(BuildConfig.TYPE)
        val appKey =
            if (isDebug) getString(R.string.rongyun_dev_key) else getString(R.string.rongyun_online_key)
        val areaCode = AreaCode.NA

        val config: PushConfig = PushConfig.Builder()
            .enableFCM(true)
            .build()
        RongPushClient.setPushConfig(config)
        val initOption = InitOption.Builder()
            .setAreaCode(areaCode)
            .enablePush(true)
            .setNaviServer("nav.us-light-edge.com")
            .build()
        RongCoreClient.setServerInfo("nav.us-light-edge.com", null)
        IMCenter.init(this, appKey, initOption)
        initAppsFlyer()
        initHttpConfig()
        initDotInit()
        openUpBuyMember = OpenUpBuyMember()
        IMRegidterPayListener.registerListener(openUpBuyMember)
    }

    /**
     * 判断当前进程是否是主进程
     */
    private fun isMainProcessName():Boolean{
        val manager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val processes = manager.runningAppProcesses

        val pid = Process.myPid()
        var processName = ""

        for (process in processes) {
            if (process.pid == pid) {
                processName = process.processName
                break
            }
        }
        return processName.equals(BuildConfig.APPLICATION_ID)

    }
    private fun initHttpConfig(){
        val httpRequestUrl = BuildConfig.HTTP_REQUEST_URl
        BaseConfig.getInstance.init(
            this,
            debug = isDebug,
            printLog = isDebug,
            debugUrl = httpRequestUrl,
            url = httpRequestUrl,
            successCode = "0",
            successCodeName = "code",
            successMsgName = "msg",
            pageName = "pageNum",
            pageSizeName = "pageSize",
            isHttpFailToast = true,
            titleBold = true,
            URLDecoder = false
        )
        BaseConfig.getInstance.setString(SpName.source, source)
        BaseConfig.getInstance.addHead("basicParams", CommonHttpResutHead.getHead().toString())
    }
    private fun initDotInit() {
        DotInit.init().setImDotExecuteListener(object : ImDotExecuteListener {
            override fun execute(eventName: String, jsonObject: JSONObject?) {
                DotLogUtil.setEventName(eventName).addJSONObject(jsonObject).commit()
            }

            override fun oldExecute(type: Int, content: String) {
                CommonRequest.commonNotify(type,content)
            }
        })
    }

    /**
     * 根据bundle初始化
     * @param string
     */
    private fun initTextAndFormal(string: String) {
        Log.e("initTextAndFormal", string)
        isDebug = string == "yyb"
        source = string
    }


    private fun initAppsFlyer() {
        AppsFlyerLib.getInstance()
            .init(BuildConfig.AF_TOKEN, object : AppsFlyerConversionListener {
                override fun onConversionDataSuccess(conversionData: MutableMap<String, Any>?) {
                    val jsonObject = JSONObject()
                    if (conversionData?.containsKey("is_incentivized") == true) {
                        jsonObject.put("is_incentivized", conversionData["is_incentivized"])
                    }
                    if (conversionData?.containsKey("af_ip") == true) {
                        jsonObject.put("af_ip", conversionData["af_ip"])
                    }
                    if (conversionData?.containsKey("is_first_launch") == true) {
                        jsonObject.put("is_first_launch", conversionData["is_first_launch"])
                    }
                    if (conversionData?.containsKey("install_time") == true) {
                        jsonObject.put("install_time", conversionData["install_time"])
                    }
                    if (conversionData?.containsKey("media_source") == true) {
                        jsonObject.put("media_source", conversionData["media_source"])
                    }
                    if (conversionData?.containsKey("advertising_id") == true) {
                        jsonObject.put("advertising_id", conversionData["advertising_id"])
                    }
                    if (conversionData?.containsKey("af_status") == true) {
                        jsonObject.put("af_status", conversionData["af_status"])
                    }
                    if (conversionData?.containsKey("af_os_version") == true) {
                        jsonObject.put("af_os_version", conversionData["af_os_version"])
                    }
                    if (conversionData?.containsKey("af_ad_id") == true) {
                        jsonObject.put("af_ad_id", conversionData["af_ad_id"])
                    }
                    if (conversionData?.containsKey("campaign") == true) {
                        jsonObject.put("campaign", conversionData["campaign"])
                    }
                    if (conversionData?.containsKey("af_adset_id") == true) {
                        jsonObject.put("af_adset_id", conversionData["af_adset_id"])
                    }
                    if (conversionData?.containsKey("af_channel") == true) {
                        jsonObject.put("af_channel", conversionData["af_channel"])
                    }
                    if (conversionData?.containsKey("af_c_id") == true) {
                        jsonObject.put("af_c_id", conversionData["af_c_id"])
                    }
                    if (conversionData?.containsKey("agency") == true) {
                        jsonObject.put("agency", conversionData["agency"])
                    }
                    if (conversionData?.containsKey("os") == true) {
                        jsonObject.put("os", conversionData["os"])
                    }
                    if (conversionData?.containsKey("af_lang") == true) {
                        jsonObject.put("af_lang", conversionData["af_lang"])
                    }
                    if (conversionData?.containsKey("cost_cents_USD") == true) {
                        jsonObject.put("cost_cents_USD", conversionData["cost_cents_USD"])
                    }
                    if (conversionData?.containsKey("af_adset") == true) {
                        jsonObject.put("af_adset", conversionData["af_adset"])
                    }
                    if (conversionData?.containsKey("af_ad") == true) {
                        jsonObject.put("af_ad", conversionData["af_ad"])
                    }

                    BaseConfig.getInstance.setString(SpName.channel, jsonObject.toString())
                }

                override fun onConversionDataFail(p0: String?) {
                }

                override fun onAppOpenAttribution(p0: MutableMap<String, String>?) {
                }

                override fun onAttributionFailure(p0: String?) {
                }

            }, this)
        AppsFlyerLib.getInstance().start(this)
    }


}